package cn.supermaster.management.web.service.system.impl;

import cn.supermaster.management.common.configure.SMManagementConfiguration;
import cn.supermaster.management.common.domain.SystemUser;
import cn.supermaster.management.common.response.WebResponse;
import cn.supermaster.management.common.utils.DateUtils;
import cn.supermaster.management.common.utils.ShiroUtils;
import cn.supermaster.management.common.utils.WebHelper;
import cn.supermaster.management.common.utils.file.FileUploadUtils;
import cn.supermaster.management.core.component.PasswordManager;
import cn.supermaster.management.system.service.ISystemUserService;
import cn.supermaster.management.web.service.system.ISProfileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;

/**
 * All rights Reserved, Designed By www.super-bytecode.com
 *
 * @ProjectName: supermaster-management
 * @Package: cn.supermaster.management.web.service.system.impl
 * @ClassName: SProfileServiceImpl
 * @Description: []
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2021/1/10 20:45
 * @Version: V1.0
 * @Copyright: 2021 www.super-bytecode.comn Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@Service
public class SProfileServiceImpl implements ISProfileService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String prefix = "system/user/profile";

    @Autowired
    private ISystemUserService userService;

    @Autowired
    private PasswordManager passwordService;

    /**
     * @Description: [跳转到个人业务界面]
     * <p></P>
     * @Title: skipProfileHtml
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: modelMap
     * @Return: java.lang.String
     */
    @Override
    public String skipProfileHtml(ModelMap modelMap) {
        // 获取用户信息
        SystemUser user = ShiroUtils.getSystemUser();
        modelMap.put("user", user);
        // 获取用户角色组信息
        String roleGroup = userService.selectUserRoleGroup(user.getUserId());
        modelMap.put("roleGroup", roleGroup);
        // 获取用户岗位组信息
        String postGroup = userService.selectUserPostGroup(user.getUserId());
        modelMap.put("postGroup", postGroup);
        //
        return prefix + "/profile";
    }

    /**
     * @Description: [跳转到用户修改密码界面]
     * <p></P>
     * @Title: skipPesetPassword
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: modelMap
     * @Return: java.lang.String
     */
    @Override
    public String skipPesetPassword(ModelMap modelMap) {
        // 获取用户信息
        SystemUser user = getSystemUserInfo();
        modelMap.put("user", user);

        return prefix + "/resetPwd";
    }

    /**
     * @Description: [跳转到用户信息修改界面]
     * <p></P>
     * @Title: skipUserModifyHtml
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: modelMap
     * @Return: java.lang.String
     */
    @Override
    public String skipUserModifyHtml(ModelMap modelMap) {
        // 获取用户信息
        SystemUser user = getSystemUserInfo();
        modelMap.put("user", user);
        return prefix + "/edit";
    }

    /**
     * @Description: [跳转到用户头像修改界面]
     * <p></P>
     * @Title: skipUserAvatarHtml
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: modelMap
     * @Return: java.lang.String
     */
    @Override
    public String skipUserAvatarHtml(ModelMap modelMap) {
        // 获取用户信息
        SystemUser user = getSystemUserInfo();
        modelMap.put("user", user);
        return prefix + "/avatar";
    }

    /*
     * ================================================
     *  页面跳转功能实现
     * ================================================
     */

    /**
     * @Description: [用户密码验证]
     * <p></P>
     * @Title: doCheckPassword
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: password
     * @Return: boolean
     */
    @Override
    public boolean doCheckPassword(String password) {
        SystemUser shiroUser = getShiroUserInfo();
        boolean matches = passwordService.matches(shiroUser, password);
        //
        return matches;
    }

    /**
     * @Description: [修改用户密码]
     * <p></P>
     * @Title: doResetAccountPassword
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: source 旧密码
     * @Param: target 新密码
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doResetPassword(String source, String target) {
        // 获取用户信息
        SystemUser shiroUser = getShiroUserInfo();
        // 修改前始密码验证
        boolean matches = passwordService.matches(shiroUser, source);
        if (!matches) {
            return WebHelper.error("修改密码失败，旧密码错误");
        }

        // 修改后密码验证
        matches = passwordService.matches(shiroUser, target);
        if (matches) {
            return WebHelper.error("新密码不能与旧密码相同");
        }
        //
        String userName = shiroUser.getUserName();//获取用户信息（登录用户名）
        String salt = shiroUser.getSalt();//获取用户加密盐值
        shiroUser.setSalt(ShiroUtils.randomSalt());
        // 加密用户密码
        String encryptPassword = passwordService.encryptPassword(userName, target, salt);
        shiroUser.setPassword(encryptPassword);
        shiroUser.setPwdUpdateDate(DateUtils.getNowDate());
        //
        if (userService.resetUserPwd(shiroUser) > 0) {
            SystemUser systemUser = userService.selectUserById(shiroUser.getUserId());
            ShiroUtils.setSystemUser(systemUser);
            return WebHelper.success();
        }

        return WebHelper.error("修改密码异常，请联系管理员");
    }

    /**
     * @Description: [修改用户信息]
     * <p></P>
     * @Title: doModifyUserInformation
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: user
     * @Return: cn.supermaster.management.common.response.WebResult
     * @Throws:
     */
    @Override
    public WebResponse doModifyUserInformation(SystemUser user) {
        // 获取用户信息
        SystemUser shiroUser = getShiroUserInfo();
        // 对当前用户信息重新赋值
        shiroUser.setNickName(user.getNickName());
        shiroUser.setEmail(user.getEmail());
        shiroUser.setMobile(user.getMobile());
        shiroUser.setSex(user.getSex());

        // 执行用户信息修改操作
        int rows = userService.updateUserInfo(shiroUser);
        if (rows > 0) {
            Long userId = shiroUser.getUserId();
            SystemUser systemUser = userService.selectUserById(userId);
            ShiroUtils.setSystemUser(systemUser);
            return WebHelper.success();
        }

        return WebHelper.error();
    }

    /**
     * @Description: [修改用户头像信息]
     * <p></P>
     * @Title: doModifyAvatarInformation
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: avatarFile
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doModifyAvatarInformation(MultipartFile avatarFile) {
        // 获取用户信息
        SystemUser shiroUser = getShiroUserInfo();
        try {
            // 头像为空，直接返回失败
            if (!avatarFile.isEmpty()) {
                throw new IllegalArgumentException("用户头像信息不能为空！");
            }

            // 获取用户头像信息
            String avatarPath = SMManagementConfiguration.getAvatarPath();//获取用户头像路径
            String avatar = FileUploadUtils.upload(avatarPath, avatarFile);
            shiroUser.setAvatar(avatar);

            // 修改用户信息
            if (userService.updateUserInfo(shiroUser) > 0) {
                Long userId = shiroUser.getUserId();
                SystemUser systemUser = userService.selectUserById(userId);
                ShiroUtils.setSystemUser(systemUser);
                return WebHelper.success();
            }

            return WebHelper.error();
        } catch (Exception e) {
            logger.error("修改头像失败，", e.getMessage());
            return WebHelper.error(e.getMessage());
        }
    }

    /*
     * ================================================
     *  通用模块支撑数据方法
     * ================================================
     */

    /**
     * @Description: [获取系统用户信息]
     * <p></P>
     * @Title: getSystemUserId
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Return: java.lang.Long
     */
    private SystemUser getSystemUserInfo() {
        // 获取用户信息
        SystemUser shiroUser = getShiroUserInfo();
        Long userId = shiroUser.getUserId();
        //
        SystemUser user = userService.selectUserById(userId);
        return user;
    }

    /**
     * @Description: [获取Shiro用户信息]
     * <p></P>
     * @Title: getShiroUserInfo
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Return: cn.supermaster.management.common.domain.SystemUser
     */
    private SystemUser getShiroUserInfo() {
        // 获取Shiro用户信息
        SystemUser shiroUser = ShiroUtils.getSystemUser();
        return shiroUser;
    }
}